package com.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waimai.Dto.SetmealDto;
import com.waimai.common.R;
import com.waimai.domain.Category;
import com.waimai.domain.Setmeal;
import com.waimai.domain.SetmealDish;
import com.waimai.service.CategoryService;
import com.waimai.service.SetmealDishService;
import com.waimai.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    SetmealService setmealService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealDishService setmealDish;


    @PutMapping
    public R<String> save(SetmealDto setmealDto){

        setmealService.sss(setmealDto);
        return R.success("1");
    }
    //套餐列表查询方法/
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页器
        Page<Setmeal> page1 =new Page<>(page,pageSize);
        //
        Page<SetmealDto> page2 =new Page<>();
        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper<>();
        //利用模糊查询like
        queryWrapper.like(name !=null,Setmeal::getName,name);
        //设置排序条件降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //用业务层接口方法完成封装
        setmealService.page(page1,queryWrapper);
        //别动一动就报错
        BeanUtils.copyProperties(page1,page2,"records");
        List<Setmeal> setmeals =page1.getRecords();
       List<SetmealDto> list =  setmeals.stream().map((item)->{
            SetmealDto setmealDto =new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Long ID =item.getCategoryId();
            Category byId = categoryService.getById(ID);
            if (byId != null){
                String name1 = byId.getName();
                setmealDto.setCategoryName(name1);
            }
            return  setmealDto;
        }).collect(Collectors.toList());
         page2.setRecords(list);
        return R.success(page2);
    }
    //删除套餐方法
    @DeleteMapping
    public R<String> delete(@RequestBody List<Long> ids){
        setmealService.romesss(ids);
        return R.success("1");
    }
    //停售方法
    //有问题 不知道哪里 返回成功缺没修改
    @PostMapping("/status/{id}")
    public R<String> status(@PathVariable Long id,int ids){
        int bian;
        Setmeal setmeal =new Setmeal();
        setmeal.setId(id);
        if (ids ==1){
            bian =0;
        }else {
            bian =1;
        }
        setmeal.setStatus(bian);
        setmealService.updateById(setmeal);
        return R.success("成功");
    }
}
